package com.demo.accessibilitykeeper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * 恢复出厂设置保护广播接收器
 */
public class FactoryResetProtectionBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "FactoryResetProtectionBR";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            String action = intent.getAction();
            Log.d(TAG, "🔍 BROADCAST_RECEIVED - Action: " + action);

            if (action != null) {
                switch (action) {
                    case "android.intent.action.FACTORY_RESET":
                        handleFactoryReset(context, intent);
                        break;
                    case "android.intent.action.MASTER_CLEAR":
                        handleMasterClear(context, intent);
                        break;
                    case Intent.ACTION_REBOOT:
                        handleReboot(context, intent);
                        break;
                    case Intent.ACTION_SHUTDOWN:
                        handleShutdown(context, intent);
                        break;
                    case "android.intent.action.FACTORY_RESET_PROTECTION":
                        handleFactoryResetProtection(context, intent);
                        break;
                    default:
                        Log.d(TAG, "🔍 UNKNOWN_ACTION - " + action);
                        break;
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "Error in broadcast receiver", e);
        }
    }

    /**
     * 处理恢复出厂设置
     */
    private void handleFactoryReset(Context context, Intent intent) {
        try {
            Log.w(TAG, "🚨 FACTORY_RESET_DETECTED - Attempting protection");
            recordFactoryResetAttempt(context);
            
            // 尝试阻止恢复出厂设置
            preventFactoryReset(context);
            
            // 启动保护服务
            startProtectionServices(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error handling factory reset", e);
        }
    }

    /**
     * 处理主清除
     */
    private void handleMasterClear(Context context, Intent intent) {
        try {
            Log.w(TAG, "🚨 MASTER_CLEAR_DETECTED - Attempting protection");
            recordMasterClearAttempt(context);
            
            // 尝试阻止主清除
            preventMasterClear(context);
            
            // 启动保护服务
            startProtectionServices(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error handling master clear", e);
        }
    }

    /**
     * 处理重启
     */
    private void handleReboot(Context context, Intent intent) {
        try {
            Log.w(TAG, "🔄 REBOOT_DETECTED - Preparing protection");
            recordRebootAttempt(context);
            
            // 准备重启保护
            prepareRebootProtection(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error handling reboot", e);
        }
    }

    /**
     * 处理关机
     */
    private void handleShutdown(Context context, Intent intent) {
        try {
            Log.w(TAG, "🔌 SHUTDOWN_DETECTED - Preparing protection");
            recordShutdownAttempt(context);
            
            // 准备关机保护
            prepareShutdownProtection(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error handling shutdown", e);
        }
    }

    /**
     * 处理恢复出厂设置保护
     */
    private void handleFactoryResetProtection(Context context, Intent intent) {
        try {
            Log.w(TAG, "🛡️ FACTORY_RESET_PROTECTION_TRIGGERED");
            recordFactoryResetProtectionTriggered(context);
            
            // 执行保护措施
            executeFactoryResetProtection(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error handling factory reset protection", e);
        }
    }

    /**
     * 阻止恢复出厂设置
     */
    private void preventFactoryReset(Context context) {
        try {
            Log.w(TAG, "🛡️ PREVENTING_FACTORY_RESET - Multiple methods");
            
            // 方式1: 发送保护广播
            sendProtectionBroadcast(context, "FACTORY_RESET_BLOCKED");
            
            // 方式2: 启动保护服务
            startProtectionServices(context);
            
            // 方式3: 记录保护事件
            recordProtectionEvent(context, "factory_reset_prevented");
            
        } catch (Exception e) {
            Log.e(TAG, "Error preventing factory reset", e);
        }
    }

    /**
     * 阻止主清除
     */
    private void preventMasterClear(Context context) {
        try {
            Log.w(TAG, "🛡️ PREVENTING_MASTER_CLEAR - Multiple methods");
            
            // 方式1: 发送保护广播
            sendProtectionBroadcast(context, "MASTER_CLEAR_BLOCKED");
            
            // 方式2: 启动保护服务
            startProtectionServices(context);
            
            // 方式3: 记录保护事件
            recordProtectionEvent(context, "master_clear_prevented");
            
        } catch (Exception e) {
            Log.e(TAG, "Error preventing master clear", e);
        }
    }

    /**
     * 准备重启保护
     */
    private void prepareRebootProtection(Context context) {
        try {
            Log.d(TAG, "🔄 PREPARING_REBOOT_PROTECTION");
            
            // 保存保护状态
            saveProtectionState(context, "reboot_protection");
            
            // 启动保护服务
            startProtectionServices(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error preparing reboot protection", e);
        }
    }

    /**
     * 准备关机保护
     */
    private void prepareShutdownProtection(Context context) {
        try {
            Log.d(TAG, "🔌 PREPARING_SHUTDOWN_PROTECTION");
            
            // 保存保护状态
            saveProtectionState(context, "shutdown_protection");
            
            // 启动保护服务
            startProtectionServices(context);
            
        } catch (Exception e) {
            Log.e(TAG, "Error preparing shutdown protection", e);
        }
    }

    /**
     * 执行恢复出厂设置保护
     */
    private void executeFactoryResetProtection(Context context) {
        try {
            Log.w(TAG, "🛡️ EXECUTING_FACTORY_RESET_PROTECTION");
            
            // 方式1: 启动保护服务
            startProtectionServices(context);
            
            // 方式2: 发送保护广播
            sendProtectionBroadcast(context, "FACTORY_RESET_PROTECTION_ACTIVE");
            
            // 方式3: 记录保护事件
            recordProtectionEvent(context, "factory_reset_protection_executed");
            
        } catch (Exception e) {
            Log.e(TAG, "Error executing factory reset protection", e);
        }
    }

    /**
     * 启动保护服务
     */
    private void startProtectionServices(Context context) {
        try {
            Log.d(TAG, "🚀 STARTING_PROTECTION_SERVICES");
            
            // 启动无障碍服务
            Intent accessibilityIntent = new Intent(context, AccessibilityKeeperService.class);
            context.startService(accessibilityIntent);
            
            // 启动保活服务
            Intent keepAliveIntent = new Intent(context, KeepAliveService.class);
            context.startService(keepAliveIntent);
            
            // 启动前台服务
            Intent foregroundIntent = new Intent(context, ForegroundService.class);
            context.startService(foregroundIntent);
            
            Log.i(TAG, "✅ PROTECTION_SERVICES_STARTED");
            
        } catch (Exception e) {
            Log.e(TAG, "Error starting protection services", e);
        }
    }

    /**
     * 发送保护广播
     */
    private void sendProtectionBroadcast(Context context, String action) {
        try {
            Intent protectionIntent = new Intent("com.demo.accessibilitykeeper.PROTECTION_ACTIVE");
            protectionIntent.putExtra("action", action);
            protectionIntent.putExtra("timestamp", System.currentTimeMillis());
            context.sendBroadcast(protectionIntent);
            
            Log.i(TAG, "📡 PROTECTION_BROADCAST_SENT - " + action);
            
        } catch (Exception e) {
            Log.e(TAG, "Error sending protection broadcast", e);
        }
    }

    /**
     * 保存保护状态
     */
    private void saveProtectionState(Context context, String state) {
        try {
            long currentTime = System.currentTimeMillis();
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putString("last_protection_state", state)
                .putLong("last_protection_time", currentTime)
                .putBoolean("protection_active", true)
                .apply();
            
            Log.i(TAG, "💾 PROTECTION_STATE_SAVED - " + state);
            
        } catch (Exception e) {
            Log.e(TAG, "Error saving protection state", e);
        }
    }

    /**
     * 记录保护事件
     */
    private void recordProtectionEvent(Context context, String event) {
        try {
            long currentTime = System.currentTimeMillis();
            int eventCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("protection_event_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putString("last_protection_event", event)
                .putLong("last_protection_event_time", currentTime)
                .putInt("protection_event_count", eventCount)
                .apply();
            
            Log.i(TAG, "📝 PROTECTION_EVENT_RECORDED - " + event + " (Count: " + eventCount + ")");
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording protection event", e);
        }
    }

    /**
     * 记录恢复出厂设置尝试
     */
    private void recordFactoryResetAttempt(Context context) {
        try {
            long currentTime = System.currentTimeMillis();
            int attemptCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("factory_reset_attempt_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putLong("last_factory_reset_attempt_time", currentTime)
                .putInt("factory_reset_attempt_count", attemptCount)
                .apply();
            
            Log.i(TAG, "📝 FACTORY_RESET_ATTEMPT_RECORDED - Count: " + attemptCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording factory reset attempt", e);
        }
    }

    /**
     * 记录主清除尝试
     */
    private void recordMasterClearAttempt(Context context) {
        try {
            long currentTime = System.currentTimeMillis();
            int attemptCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("master_clear_attempt_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putLong("last_master_clear_attempt_time", currentTime)
                .putInt("master_clear_attempt_count", attemptCount)
                .apply();
            
            Log.i(TAG, "📝 MASTER_CLEAR_ATTEMPT_RECORDED - Count: " + attemptCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording master clear attempt", e);
        }
    }

    /**
     * 记录重启尝试
     */
    private void recordRebootAttempt(Context context) {
        try {
            long currentTime = System.currentTimeMillis();
            int attemptCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("reboot_attempt_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putLong("last_reboot_attempt_time", currentTime)
                .putInt("reboot_attempt_count", attemptCount)
                .apply();
            
            Log.i(TAG, "📝 REBOOT_ATTEMPT_RECORDED - Count: " + attemptCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording reboot attempt", e);
        }
    }

    /**
     * 记录关机尝试
     */
    private void recordShutdownAttempt(Context context) {
        try {
            long currentTime = System.currentTimeMillis();
            int attemptCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("shutdown_attempt_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putLong("last_shutdown_attempt_time", currentTime)
                .putInt("shutdown_attempt_count", attemptCount)
                .apply();
            
            Log.i(TAG, "📝 SHUTDOWN_ATTEMPT_RECORDED - Count: " + attemptCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording shutdown attempt", e);
        }
    }

    /**
     * 记录恢复出厂设置保护触发
     */
    private void recordFactoryResetProtectionTriggered(Context context) {
        try {
            long currentTime = System.currentTimeMillis();
            int triggerCount = context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .getInt("factory_reset_protection_trigger_count", 0) + 1;
            
            context.getSharedPreferences("factory_reset_protection_prefs", Context.MODE_PRIVATE)
                .edit()
                .putLong("last_factory_reset_protection_trigger_time", currentTime)
                .putInt("factory_reset_protection_trigger_count", triggerCount)
                .apply();
            
            Log.i(TAG, "📝 FACTORY_RESET_PROTECTION_TRIGGER_RECORDED - Count: " + triggerCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording factory reset protection trigger", e);
        }
    }
}
